package com.apetrenko.avaya.callstore.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;

public class SettingsPanel extends Composite implements AsyncCallback<Config> {

	private class SaveButtonHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent aEvent) {
			save();
		}

	}

	private static final int MAX_ROWS = 10;
	private FlexTable iTable = new FlexTable();
	private TextBox iArchIntervalBox = new TextBox();
	private TextBox iVRLPathBox = new TextBox();
	private TextBox iArchivePathBox = new TextBox();
	
	private Button iSaveButton = new Button("Save");
	
	private Config iConfig;
	private SettingsServiceAsync iService;

	public SettingsPanel() {
		for (int i = 0; i < MAX_ROWS; i++) {
			iTable.insertRow(0);
		}
		
		//FlexCellFormatter vFormatter = (FlexCellFormatter) iTable.getCellFormatter();
		iTable.setWidget(1, 0,  new Label("Archivation interval (secs):"));
		iTable.setWidget(2, 0,  new Label("Path to VRL directory:"));
		iTable.setWidget(3, 0,  new Label("Path to archive directory:"));
		
		iTable.setWidget(1, 1, iArchIntervalBox);
		iTable.setWidget(2, 1, iVRLPathBox);
		iTable.setWidget(3, 1, iArchivePathBox);
		
		iSaveButton.addClickHandler(new SaveButtonHandler());
		iTable.setWidget(MAX_ROWS - 1 , 1, iSaveButton);
		
		initWidget(iTable);
		reload();
	}

	@Override
	public void onFailure(Throwable aCaught) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSuccess(Config aResult) {
		setConfig(aResult);
		
	}
	
	private void setConfig(Config aConfig) {
		iConfig = aConfig;
		refreshFieldValues();
	}
	
	private void refreshFieldValues(){
		iArchIntervalBox.setText("" + iConfig.getArchivePeriod());
		iVRLPathBox.setText(iConfig.getVrlPath());
		iArchivePathBox.setText(iConfig.getArchivePath());
	}

	public void reload(){
		if (iService == null){
			iService = GWT.create(SettingsService.class);
		}
		iService.getConfig(this);
	}
	
	public void save(){
		storeFieldValues();
		if (iService == null){
			iService = GWT.create(SettingsService.class);
		}
		iService.setConfig(iConfig, this);
	}

	private void storeFieldValues() {
		iConfig.setArchivePeriod(Integer.parseInt(iArchIntervalBox.getText()));
		iConfig.setVrlPath(iVRLPathBox.getText());
		iConfig.setArchivePath(iArchivePathBox.getText());
	}

}
